package com.ghy.springbootsentinel;

import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientAssignConfig;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfig;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfigManager;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 卢佳新
 * @version: v1.0
 * @description: com.ghy.springbootsentinel
 * @date:2022/1/3 15:30
 * @Motto 不积跬步，无以至千里；不积小流，无以成江海。
 */
public class FlowRuleInitFunc  implements InitFunc {

    private final String nacosAddress="localhost:8848";
    private final String groupId="SENTINEL_GROUP";//nacos分组
    private final String dataId="-flow-rules";//nacos的data Id配置

    private final String clusterServerHost="localhost";
    private final int clusterServerPort=9999;
    private final int requestTimeOut=20000;
    private final String appName="App-Test";

    @Override
    public void init() throws Exception {
       // initFlowRule();
        loadClusterConfig();
        registerFlowRule();
    }

    private static void initFlowRule(){
        List<FlowRule> rules=new ArrayList<> ();
        FlowRule flowRule=new FlowRule();
        flowRule.setResource("doTest"); //针对那个资源设置规则
        flowRule.setGrade( RuleConstant.FLOW_GRADE_QPS);//QPS或者并发数
        flowRule.setCount(5); //QPS=5
        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }
    //加载集群限流配置
    private void loadClusterConfig(){
        ClusterClientAssignConfig assignConfig=new ClusterClientAssignConfig();
        assignConfig.setServerHost(clusterServerHost); //放到配置中心
        assignConfig.setServerPort(clusterServerPort);
        ClusterClientConfigManager.applyNewAssignConfig(assignConfig);
        ClusterClientConfig clientConfig=new ClusterClientConfig();
        clientConfig.setRequestTimeout(requestTimeOut);  //放到配置中心
        ClusterClientConfigManager.applyNewConfig(clientConfig);
    }
    //回退
    private void registerFlowRule(){
        //从远程服务器上加载规则（nacos）
        ReadableDataSource<String, List<FlowRule>> flowRuleDs=
                new NacosDataSource<List<FlowRule>>(nacosAddress,groupId,appName+dataId,
                        source-> JSON.parseObject(source,new TypeReference<List<FlowRule>> (){}));
        FlowRuleManager.register2Property(flowRuleDs.getProperty());
    }
}
